# coding:utf-8

from django.db import models
import hashlib


def hash_password(password):
    if isinstance(password, str):
        password = password.encode('utf-8')
    return hashlib.md5(password).hexdigest().upper()


class ClientUser(models.Model):

    username = models.CharField(max_length=50, null=False, unique=True)
    password = models.CharField(max_length=255, null=False)
    gender = models.CharField(max_length=10, default='')
    age = models.CharField(default='', max_length=2)
    # 状态（is_active）
    status = models.BooleanField(default=True, db_index=True)
    created_time = models.DateField(auto_now_add=True)
    job = models.CharField(max_length=50, null=False, default='')
    email = models.EmailField(null=False, default='')
    userId = models.CharField(max_length=10, default='')

    class Meta:
        unique_together = ('username', 'password')

    def __str__(self):
        return 'username:{}'.format(self.username)

    # 使用create创建对象不会自动加密密码
    @classmethod
    def add(cls, username, password, gender='', age='', job='', email='', userId=''):
        return cls.objects.create(
            username=username,
            password=hash_password(password),
            gender=gender,
            age=age,
            job=job,
            status=True,
            email=email,
            userId=userId
        )

    '''
    用户未登录时没有User对象，所以要调用属性需要classmethod装饰器。
    classmethod 修饰符对应的函数不需要实例化，不需要 self 参数，
    但第一个参数需要是表示自身类的 cls 参数，可以来调用类的属性，类的方法，实例化对象等。
    '''

    @classmethod
    def get_user(cls, username, password):
        try:
            user = cls.objects.get(
                username=username,
                password=hash_password(password)
            )
            return user
        except:
            return None

    # 用户登陆后可以直接通过self调用user对象更改密码，所以不需要使用classmethod装饰器
    def update_password(self, old_password, new_password):
        hash_old_password = hash_password(old_password)

        if hash_old_password != self.password:
            return False

        hash_new_password = hash_password(new_password)
        self.password = hash_new_password
        self.save()
        return True

    def update_status(self):
        self.status = not self.status
        self.save()
        return True


class Collect(models.Model):
    username = models.ForeignKey(ClientUser, on_delete=models.CASCADE, related_name='collect')
    movieId = models.IntegerField(max_length=10, null=False)

    def __str__(self):
        return 'username:{},movieId:{}'.format(self.username, self.movieId)

    @classmethod
    def add(cls, username, movieId):
        return cls.objects.create(
            username=username,
            movieId=movieId
        )

